#include <board.h>
#include <rtdevice.h>
#include <drivers/i2c.h>

#ifdef RT_USING_I2C

#define DBG_LVL               DBG_LOG

#define DBG_TAG               "test_i2c_fm24v10"
#include <rtdbg.h>

#define I2C_DEVICE			"i2c1"
#define DATA_LEN			256

static uint8_t buff_w[DATA_LEN];
static struct rt_i2c_bus_device *i2c_bus;

int test_i2c_fm24v10() {

	rt_uint16_t slave_addr = 0x52; // 1010 01 0

	uint8_t buff_r[DATA_LEN] = { 0 };

	uint8_t begin_addr[] = { 0x00, 0x08 };

	i2c_bus = (struct rt_i2c_bus_device*) rt_device_find(I2C_DEVICE);

	if (i2c_bus == RT_NULL) {
		LOG_E("can't find '%s' device", I2C_DEVICE);
		return -1;
	}

	rt_size_t len;

//	// Single Byte Write
//	for (int i = 0; i < DATA_LEN; i++) {
//
//		uint8_t data[] = { 0x00, i, i + 1 }; // {高地址, 低地址, 1 byte 数据}
//
//		len = rt_i2c_master_send(i2c_bus, slave_addr, RT_I2C_WR, data,
//				ARRAY_SIZE(data));
//
//		if (len != ARRAY_SIZE(data)) {
//			LOG_E("rt_i2c_master_send failed, ret: %d", len);
//			return -RT_ERROR;
//		}
//	}
//
//	LOG_I("single byte write eeprom ok\n");

	// Multiple Bytes Write

	for (int i = 0; i < DATA_LEN; i++) {
		buff_w[i] = i;
	}

	struct rt_i2c_msg msgs_w[] = { { slave_addr, RT_I2C_WR, 2, begin_addr }, {
			slave_addr, RT_I2C_WR | RT_I2C_NO_START, DATA_LEN, buff_w } };

	len = rt_i2c_transfer(i2c_bus, msgs_w, ARRAY_SIZE(msgs_w));

	if (len != ARRAY_SIZE(msgs_w)) {
		LOG_E("writing data failed, ret: %d", len);
		return -RT_ERROR;
	}
	LOG_I("multiple bytes write eeprom ok\n");

	rt_thread_mdelay(100);

	// Selective (Random) Read
	rt_memset(buff_r, 0, DATA_LEN);

	struct rt_i2c_msg msgs_r[] = { { slave_addr, RT_I2C_WR, 2, begin_addr }, {
			slave_addr, RT_I2C_RD, DATA_LEN, buff_r } };

	len = rt_i2c_transfer(i2c_bus, msgs_r, ARRAY_SIZE(msgs_r));

	if (len < 0) {
		LOG_E("rt_i2c_transfer failed, ret: %d", len);
		return -2;
	}

	for (uint32_t i = 0; i < DATA_LEN; i++) {
		rt_kprintf("[%03d]: %3d\n", i, buff_r[i]);
	}

	LOG_I("multiple bytes read eeprom ok\n");

	return 0;
}

MSH_CMD_EXPORT(test_i2c_fm24v10, test i2c_fm24v10);
//INIT_APP_EXPORT(test_i2c_fm24v10);

#endif // RT_USING_I2C

